package models

import (
	"fmt"
	"time"

	"gitee.com/zinface/go.youwant-platform/external/utils"
)

type Pastebin struct {
	Id        int       `json:"id"`
	Title     string    `json:"title"`
	Content   string    `json:"content"`
	Author    string    `json:"author"`
	Tags      string    `json:"tags"`
	Syntax    string    `json:"syntax"`
	Theme     string    `json:"theme"`
	CreatedAt time.Time `json:"created_at"`
	Uuid      string    `json:"uuid"`
	Upid      string    `json:"puid"`
	Pastebin  []Pastebin
}

// ---------------------------------------------------------------- GenerateRandomUUID

func GeneratePastebinUUID() string {
	uuid := utils.GenerateRandomMd5()

	ps := FindPastebin(uuid)
	if len(ps) > 0 {
		fmt.Println("fuck:", uuid)
		return GeneratePastebinUUID()
	}

	fmt.Println("uuid:", uuid)
	return uuid
}

// ---------------------------------------------------------------- Pastebin

func FindPastebinUUID(uuid string) (*Pastebin, error) {
	var p = &Pastebin{}
	err := db.Where("uuid = ?", uuid).Find(&p).Error
	if err != nil {
		return nil, err
	}
	return p, nil
}

func FindPastebin(uuid string) []Pastebin {
	var ps []Pastebin
	err := db.Where("uuid = ?", uuid).Find(&ps).Error
	if err != nil {
		fmt.Println("err:", err.Error())
		return ps
	}
	return ps
}

func FindPastebins() []Pastebin {
	var ps []Pastebin
	if err := db.Find(&ps).Error; err != nil {
		return ps
	}
	return ps
}

// ------------------------------ Other

func NewPastebin(title string, content string, author string, tags string, syntax string, theme string) *Pastebin {
	return &Pastebin{
		Title:     title,
		Content:   content,
		Author:    author,
		Syntax:    syntax,
		Theme:     theme,
		Tags:      tags,
		CreatedAt: time.Now(),
		Uuid:      GeneratePastebinUUID(),
	}
}

func (p *Pastebin) Save() error {
	return db.Create(&p).Error
}

func (p *Pastebin) Delete() error {
	return db.Delete(p).Error
}
